package com.czwj.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.czwj.annotation.SystemControllerLog;
import com.czwj.entities.DataGridData;
import com.czwj.entities.Form;
import com.czwj.entities.OperateResult;
import com.czwj.entities.PageBean;
import com.czwj.entities.PlanDaily;
import com.czwj.entities.PlanMain;
import com.czwj.entities.ProjectItem;
import com.czwj.entities.UserInfo;
import com.czwj.service.FormService;
import com.czwj.service.PlanDailyService;
import com.czwj.service.PlanMainService;
import com.czwj.service.ProjectItemService;
import com.czwj.util.GsonUtil;
import com.czwj.util.TextUtil;
import com.czwj.util.WechatUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import net.sf.json.JSONObject;

@Controller
public class PlanMainAction{
	@Resource
	PlanMainService planMainService;
	
	@Resource
	PlanDailyService planDailyService;
	
	@Resource
	ProjectItemService projectItemService;
	
	@Resource
	FormService formService;
	
	@Value("${review_model_code}")
	private String model_code;
	
	SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分");
	
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
	
	@RequestMapping(value = "/planmain.do",method = RequestMethod.GET)
	@ResponseBody
	public DataGridData<PlanMain> planMain(@RequestParam(value = "page",required = false) String page,
			@RequestParam(value = "rows",required = false) String rows,
			@RequestParam(value = "status",required = false) String status,
			@RequestParam(value = "startdate",required = false) String startdate,
			@RequestParam(value = "enddate",required = false) String enddate,
			@RequestParam(value = "projectitemchildid",required = false) String projectitemchildid,
			@RequestParam(value = "projectitemid",required = false) String projectitemid){
		DataGridData<PlanMain> result = new DataGridData();
		Map<String,Object> map = new HashMap<String,Object>();
		PageBean pageBean = null;
		if(TextUtil.isNotEmpty(page) && TextUtil.isNotEmpty(rows)){
			pageBean = new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
		}
		if(pageBean != null){
			map.put("start",pageBean.getStart());
			map.put("size",pageBean.getPageSize());
		}
		if(TextUtil.isNotEmpty(status)){
			map.put("status",status);
		}
		if(TextUtil.isNotEmpty(startdate)){
			map.put("startdate",startdate);
		}
		if(TextUtil.isNotEmpty(enddate)){
			map.put("enddate",enddate);
		}
		if(TextUtil.isNotEmpty(projectitemid) && !projectitemid.equals("0")){
			map.put("projectitemid",projectitemid);
		}
		if(TextUtil.isNotEmpty(projectitemchildid) && !projectitemchildid.equals("0")){
			map.put("projectitemchildid",projectitemchildid);
		}
		Subject currentUser = SecurityUtils.getSubject();
		int userid = ((UserInfo)currentUser.getSession().getAttribute("userInfo")).getId();
		map.put("createrid",userid);
		List<PlanMain> list = planMainService.searchbyprojectitem(map);
		result.setRows(list);
		result.setTotal(planMainService.countbyprojectitem(map));
		return result;
	}
	
	@RequestMapping(value = "defaultPlanMainName",method = RequestMethod.GET)
	@ResponseBody
	public void defaultPlanMainName(@RequestParam(value = "id",required = true) int id,HttpServletResponse response)
			throws IOException{
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("projectitemid",id);
		int cnt = planMainService.searchbyprojectitem(map).size();
		GsonUtil.toJson(response,TextUtil.toChinese((cnt + 1) + ""));
	}
	
	@RequestMapping(value = "defaultPlanMainNameChild",method = RequestMethod.GET)
	@ResponseBody
	public void defaultPlanMainNameChild(@RequestParam(value = "id",required = true) int id,
			HttpServletResponse response) throws IOException{
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("projectitemchildid",id);
		int cnt = planMainService.searchbyprojectitem(map).size();
		GsonUtil.toJson(response,TextUtil.toChinese((cnt + 1) + ""));
	}
	
	@SystemControllerLog(description = "修改主计划")
	@RequestMapping(value = "/planMainSave.do",method = RequestMethod.POST)
	@ResponseBody
	public OperateResult planMainSave(@RequestBody PlanMain planMain,HttpServletRequest request) throws Exception{
		OperateResult result = new OperateResult();
		int count = 0;
		if(planMain.getId() != null && planMain.getId() > 0){
			count = planMainService.update(planMain);
		}else{
			Subject currentUser = SecurityUtils.getSubject();
			planMain.setCreaterid(((UserInfo)currentUser.getSession().getAttribute("userInfo")).getId());
			planMain.setCreatedate(new Date());
			planMain.setCreateip(request.getRemoteAddr());
			planMain.setFinishpercent(0d);
			planMain.setStatus(6);
			count = planMainService.insert(planMain);
		}
		ProjectItem projectItem = projectItemService.selectByPrimaryKey(planMain.getProjectitemid());
		for(UserInfo user:projectItem.getLevel2()){
			JSONObject data = WechatUtil.setReviewData(projectItem.getName() + " 主计划",sdf2.format(new Date()));
			sendReview(user,data);
		}
		result.setSuccess(count > 0);
		return result;
	}
	
	@SystemControllerLog(description = "禁用主计划")
	@RequestMapping(value = "planMainDelete.do",method = RequestMethod.POST)
	@ResponseBody
	public OperateResult deletePlanMain(@RequestParam("planMainid") int id){
		OperateResult result = new OperateResult();
		try{
			int count = planMainService.updateStatus(id);
			result.setSuccess(count > 0);
			return result;
		}
		catch(Exception e){
			// TODO Auto-generated catch block
			result.setSuccess(false);
			return result;
		}
	}
	
	@SystemControllerLog(description = "删除主计划")
	@RequestMapping(value = "planMainRemove.do",method = RequestMethod.POST)
	@ResponseBody
	public OperateResult removePlanMain(@RequestParam("id") int id){
		OperateResult result = new OperateResult();
		try{
			int count = planMainService.remove(id);
			result.setSuccess(count > 0);
			return result;
		}
		catch(Exception e){
			// TODO Auto-generated catch block
			result.setSuccess(false);
			return result;
		}
	}
	
	@RequestMapping(value = "planmain/remainpercent",method = RequestMethod.GET)
	@ResponseBody
	public String checkRemainpercent(@RequestParam("projectitemid") int id,@RequestParam("planid") int planid){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("projectitemid",id);
		map.put("planid",planid);
		String percent = planMainService.remainpercent(map);
		return percent;
	}
	
	@RequestMapping(value = "planmain/remainpercentchild",method = RequestMethod.GET)
	@ResponseBody
	public String remainpercentchild(@RequestParam("projectitemchildid") int id,@RequestParam("planid") int planid){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("projectitemchildid",id);
		map.put("planid",planid);
		String percent = planMainService.remainpercentchild(map);
		return percent;
	}
	
	@RequestMapping(value = "planmain/unfinishpercent",method = RequestMethod.GET)
	@ResponseBody
	public String checkUnfinishpercent(@RequestParam("mainid") int mainid){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("mainid",mainid);
		PlanMain main = planMainService.selectByPrimaryKey(mainid);
		String percent = String.valueOf(100d - (main.getFinishpercent() == null?0:main.getFinishpercent()));
		return percent;
	}
	
	@RequestMapping(value = "/review/planmain.do",method = RequestMethod.GET)
	@ResponseBody
	public DataGridData<PlanMain> reviewPlanMain(@RequestParam(value = "page",required = false) String page,
			@RequestParam(value = "rows",required = false) String rows,
			@RequestParam(value = "startdate",required = false) String startdate,
			@RequestParam(value = "enddate",required = false) String enddate,
			@RequestParam(value = "projectitemid",required = false) String projectitemid){
		DataGridData<PlanMain> result = new DataGridData();
		Map<String,Object> map = new HashMap<String,Object>();
		PageBean pageBean = null;
		if(TextUtil.isNotEmpty(page) && TextUtil.isNotEmpty(rows)){
			pageBean = new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
		}
		if(pageBean != null){
			map.put("start",pageBean.getStart());
			map.put("size",pageBean.getPageSize());
		}
		Subject currentUser = SecurityUtils.getSubject();
		UserInfo userInfo = (UserInfo)currentUser.getSession().getAttribute("userInfo");
		if(TextUtil.isNotEmpty(startdate)){
			map.put("startdate",startdate);
		}
		if(TextUtil.isNotEmpty(enddate)){
			map.put("enddate",enddate);
		}
		if(TextUtil.isNotEmpty(projectitemid) && !projectitemid.equals("0")){
			map.put("projectitemid",projectitemid);
		}
		int roleid = userInfo.getRoleid();
		if(roleid == 1 || roleid == 2){
			map.put("status",7);
			result.setRows(planMainService.searchbyprojectitem(map));
			result.setTotal(planMainService.countbyprojectitem(map));
		}
		if(roleid == 3){
			map.put("status",6);
			result.setRows(planMainService.searchbyprojectitem(map));
			result.setTotal(planMainService.countbyprojectitem(map));
		}
		return result;
	}
	
	@RequestMapping(value = "/reviewed/planmain.do",method = RequestMethod.GET)
	@ResponseBody
	public DataGridData<PlanMain> reviewedPlanMain(@RequestParam(value = "page",required = false) String page,
			@RequestParam(value = "rows",required = false) String rows,
			@RequestParam(value = "startdate",required = false) String startdate,
			@RequestParam(value = "enddate",required = false) String enddate,
			@RequestParam(value = "projectitemid",required = false) String projectitemid){
		DataGridData<PlanMain> result = new DataGridData();
		Map<String,Object> map = new HashMap<String,Object>();
		PageBean pageBean = null;
		if(TextUtil.isNotEmpty(page) && TextUtil.isNotEmpty(rows)){
			pageBean = new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
		}
		if(pageBean != null){
			map.put("start",pageBean.getStart());
			map.put("size",pageBean.getPageSize());
		}
		Subject currentUser = SecurityUtils.getSubject();
		UserInfo userInfo = (UserInfo)currentUser.getSession().getAttribute("userInfo");
		map.put("userid",userInfo.getId());
		if(TextUtil.isNotEmpty(startdate)){
			map.put("startdate",startdate);
		}
		if(TextUtil.isNotEmpty(enddate)){
			map.put("enddate",enddate);
		}
		if(TextUtil.isNotEmpty(projectitemid) && !projectitemid.equals("0")){
			map.put("projectitemid",projectitemid);
		}
		int roleid = userInfo.getRoleid();
		if(roleid == 1 || roleid == 2){
			map.put("status",4);
			result.setRows(planMainService.searchbyprojectitem(map));
			result.setTotal(planMainService.countbyprojectitem(map));
		}
		if(roleid == 3){
			map.put("status","4,7");
			result.setRows(planMainService.searchbyprojectitem(map));
			result.setTotal(planMainService.countbyprojectitem(map));
		}
		return result;
	}
	
	@RequestMapping(value = "/planMainReviewed.do",method = RequestMethod.GET)
	@ResponseBody
	public DataGridData<PlanMain> planMainReviewed(@RequestParam(value = "page",required = false) String page,
			@RequestParam(value = "rows",required = false) String rows){
		DataGridData<PlanMain> result = new DataGridData();
		Map<String,Object> map = new HashMap<String,Object>();
		PageBean pageBean = null;
		if(TextUtil.isNotEmpty(page) && TextUtil.isNotEmpty(rows)){
			pageBean = new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
		}
		if(pageBean != null){
			map.put("start",pageBean.getStart());
			map.put("size",pageBean.getPageSize());
		}
		Subject currentUser = SecurityUtils.getSubject();
		UserInfo userInfo = (UserInfo)currentUser.getSession().getAttribute("userInfo");
		map.put("userid",userInfo.getId());
		if(userInfo.getRoleid() == 1 || userInfo.getRoleid() == 2){
			map.put("status","3,4");
			result.setRows(planMainService.searchReviewedLevel1(map));
			result.setTotal(planMainService.countReviewedLevel1(map));
		}else if(userInfo.getRoleid() == 3){
			map.put("status","3,4,7");
			result.setRows(planMainService.searchReviewedLevel2(map));
			result.setTotal(planMainService.countReviewedLevel2(map));
		}
		return result;
	}
	
	@RequestMapping(value = "getschedule.do",method = RequestMethod.GET)
	@ResponseBody
	public void getschedule(@RequestParam(value = "projectitemid",required = true) int projectitemid,
			HttpServletResponse response) throws IOException{
		JsonArray array = new JsonArray();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("projectitemid",projectitemid);
		List<PlanMain> list = planMainService.searchbyprojectitem(map);
		for(PlanMain planMain:list){
			JsonObject object = new JsonObject();
			JsonObject object2 = new JsonObject();
			JsonArray values = new JsonArray();
			JsonArray values2 = new JsonArray();
			JsonObject value = new JsonObject();
			object.addProperty("name",planMain.getName());
			object.addProperty("desc","计划");
			object2.addProperty("name","");
			object2.addProperty("desc","实际");
			value.addProperty("from","/Date(" + sdf.format(planMain.getStartdate()) + ")/");
			value.addProperty("to","/Date(" + planMain.getEnddate() + ")/");
			value.addProperty("label","");
			value.addProperty("customClass","ganttRed");
			value.addProperty("dataObj",GsonUtil.objectToJsonStr(planMain));
			values.add(value);
			object.add("values",values);
			array.add(object);
			List<PlanDaily> dailies = planDailyService.findbymain(planMain.getId());
			for(PlanDaily planDaily:dailies){
				JsonObject value2 = new JsonObject();
				value2.addProperty("from","/Date(" + sdf.format(planDaily.getPlandate()) + ")/");
				value2.addProperty("to","/Date(" + planDaily.getPlandate() + ")/");
				if(planDaily.getReport() != null){
					value2.addProperty("label","");
					value2.addProperty("customClass","ganttblue");
				}else{
					value2.addProperty("label","");
					value2.addProperty("customClass","ganttGray");
				}
				value2.addProperty("dataObj",GsonUtil.objectToJsonStr(planDaily));
				values2.add(value2);
			}
			object2.add("values",values2);
			array.add(object2);
		}
		GsonUtil.toJson(response,array);
	}
	
	private void sendReview(UserInfo userInfo,JSONObject data){
		List<Form> forms = formService.findbyuser(userInfo.getId());
		for(Form form:forms){
			String code = WechatUtil.pushMessage(userInfo.getOpenid(),model_code,form.getFormid(),data);
			formService.deleteByPrimaryKey(form.getId());
			if(code.trim().equals("0")){
				return;
			}
		}
	}
}
